
#include "app_button.h"


// 定义每个按钮的 GPIO 端口和引脚
typedef struct {
    GPIO_TypeDef *port;
    uint16_t pin;
} APP_BUTTON_CONFIG;

APP_BUTTON_CONFIG button_configs[BUTTON_COUNT];


// 全局变量
ButtonState button_states[BUTTON_COUNT] = {BUTTON_RELEASED}; // 当前每个按钮的状态
uint32_t last_check_times[BUTTON_COUNT] = {0};               // 每个按钮上次检查时间
uint32_t debounce_delay = 50;                               // 去抖延时，单位ms


uint8_t add_button_config(uint8_t button_count, GPIO_TypeDef *port, uint16_t pin)
{
    if (button_count >= BUTTON_COUNT) 
	{
        return 1;
    }

    button_configs[button_count].port = port;
    button_configs[button_count].pin = pin;

    return 0; // 添加成功
}


void app_button_detect(void)
{
    uint32_t current_time = HAL_GetTick(); // 获取当前时间（ms）

    for (int i = 0; i < BUTTON_COUNT; i++) {
        // 检查去抖延时是否已过
        if ((current_time - last_check_times[i]) < debounce_delay) {
            continue;
        }
        last_check_times[i] = current_time;

        // 读取按钮电平
        GPIO_PinState pin_state = HAL_GPIO_ReadPin(button_configs[i].port, button_configs[i].pin);

        // 检测按钮状态变化
        if (pin_state == GPIO_PIN_RESET) 
        { // 低电平，表示按下
            if (button_states[i] == BUTTON_RELEASED) 
            {
                button_states[i] = BUTTON_PRESSED;
            }
        } 
        else 
        { // 高电平，表示释放
            if (button_states[i] == BUTTON_PRESSED) 
            {
                button_states[i] = BUTTON_RELEASED;
            }
        }
    }
}

#define BTN1_Pin GPIO_PIN_7
#define BTN1_GPIO_Port GPIOA
#define BTN2_Pin GPIO_PIN_0
#define BTN2_GPIO_Port GPIOB
#define BTN3_Pin GPIO_PIN_1
#define BTN3_GPIO_Port GPIOB

void app_button_init(void)
{
    add_button_config(0, BTN1_GPIO_Port, BTN1_Pin);
    add_button_config(1, BTN2_GPIO_Port, BTN2_Pin);
    add_button_config(2, BTN3_GPIO_Port, BTN3_Pin);
}


